<template>
  <div class="agent-edit-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? "编辑代理" : "添加代理" }}</span>
          <el-button @click="goBack">返回列表</el-button>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        v-loading="loading"
      >
        <el-form-item label="代理名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入代理名称" />
        </el-form-item>

        <el-form-item label="代理等级" prop="level">
          <el-select v-model="form.level" placeholder="请选择代理等级">
            <el-option :value="1" label="普通代理" />
            <el-option :value="2" label="高级代理" />
            <el-option :value="3" label="区域代理" />
            <el-option :value="4" label="总代理" />
          </el-select>
        </el-form-item>

        <el-form-item label="上级代理" prop="parent_id">
          <el-select
            v-model="form.parent_id"
            placeholder="请选择上级代理"
            filterable
            clearable
            :disabled="isEdit && form.has_children"
          >
            <el-option
              v-for="agent in parentOptions"
              :key="agent.id"
              :label="agent.name"
              :value="agent.id"
              :disabled="agent.id === agentId"
            />
          </el-select>
          <div v-if="isEdit && form.has_children" class="tip-text">
            <el-tag type="warning">该代理存在下级，无法更改上级</el-tag>
          </div>
        </el-form-item>

        <el-form-item label="手机号码" prop="mobile">
          <el-input
            v-model="form.mobile"
            placeholder="请输入手机号码"
            :disabled="userStore.isTest"
          />
        </el-form-item>

        <el-form-item label="关联用户" prop="user_id" required>
          <div class="user-search-box">
            <el-select
              v-model="form.user_id"
              filterable
              remote
              reserve-keyword
              placeholder="请输入用户名/手机号码搜索用户"
              :remote-method="searchUserRemote"
              :loading="userSearchLoading"
              clearable
              :disabled="userStore.isTest || isEdit"
            >
              <el-option
                v-for="item in userOptions"
                :key="item.user_id"
                :label="`${item.nick_name} (${
                  userStore.isTest
                    ? maskMobile(item.mobile)
                    : item.mobile || '无手机号'
                })`"
                :value="item.user_id"
                :disabled="item.is_agent"
              >
                <div class="user-option">
                  <span>{{ item.nick_name }}</span>
                  <span class="user-mobile">{{
                    userStore.isTest
                      ? maskMobile(item.mobile)
                      : item.mobile || "无手机号"
                  }}</span>
                  <el-tag
                    v-if="item.is_agent"
                    size="small"
                    type="warning"
                    class="agent-tag"
                    >已是代理</el-tag
                  >
                </div>
              </el-option>
            </el-select>
            <el-tooltip
              content="关联用户后，该用户将可以使用小程序的代理功能"
              placement="top"
            >
              <el-icon class="info-icon"><InfoFilled /></el-icon>
            </el-tooltip>
          </div>
          <div class="tip-text" v-if="form.user_id">
            <el-tag type="success">已选择用户ID: {{ form.user_id }}</el-tag>
          </div>
          <div class="tip-text" v-if="isEdit">
            <el-tag type="info">编辑模式下不能更改关联用户</el-tag>
          </div>
        </el-form-item>

        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入电子邮箱" />
        </el-form-item>

        <el-form-item label="代理区域" prop="region">
          <el-input v-model="form.region" placeholder="请输入代理区域" />
        </el-form-item>

        <el-form-item label="佣金比例" prop="commission_rate">
          <el-input-number
            v-model="form.commission_rate"
            :min="0"
            :max="1"
            :precision="2"
            :step="0.01"
            controls-position="right"
          />
          <span class="ml-10"
            >（上级代理佣金比例: {{ parentCommissionRate || "-" }}）</span
          >
        </el-form-item>

        <el-form-item label="激活码数量" prop="max_generation_count">
          <el-input-number
            v-model="form.max_generation_count"
            :min="0"
            :step="10"
            controls-position="right"
          />
          <span class="ml-10" v-if="isEdit"
            >（已使用: {{ form.used_generation_count || 0 }}）</span
          >
        </el-form-item>
        <el-form-item label="开卡数量">
          <el-input-number
            v-model="form.card_record"
            :min="0"
            :step="10"
            controls-position="right"
          />
          <el-button type="primary" @click="handleOpenCard">开卡</el-button>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="submitForm"
            :disabled="submitDisabled"
            >保存</el-button
          >
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>

      <!-- 编辑模式下显示代理详情信息 -->
      <div v-if="false && isEdit && form.id" class="agent-info">
        <el-divider content-position="left">代理详情信息</el-divider>
        <el-descriptions :column="3" border>
          <el-descriptions-item label="创建时间">{{
            form.create_time
          }}</el-descriptions-item>
          <el-descriptions-item label="账户余额"
            >¥{{ form.balance }}</el-descriptions-item
          >
          <el-descriptions-item label="团队规模"
            >{{ form.team_size || 0 }}人</el-descriptions-item
          >
          <el-descriptions-item label="团队业绩"
            >¥{{ form.team_performance || 0 }}</el-descriptions-item
          >
          <el-descriptions-item label="剩余激活码">{{
            form.remaining_count || 0
          }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getAgentDetail,
  addAgent,
  updateAgent,
  getAgentList,
  baseOpenCard,
} from "@/api/agents";
import { searchUsers } from "@/api/users";
import { InfoFilled } from "@element-plus/icons-vue";
import { useUserStore } from "@/store/user";

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const formRef = ref(null);
const loading = ref(false);
const parentOptions = ref([]);
// 表单数据
const form = reactive({
  name: "",
  level: 1,
  parent_id: null,
  mobile: "",
  email: "",
  region: "",
  commission_rate: 0.1,
  max_generation_count: 100,
  status: 1,
  user_id: null,
  card_record: 0, // 开卡次数
});

// 获取路由中的ID参数
const agentId = computed(() => {
  return parseInt(route.params.id) || 0;
});

// 判断是编辑还是新增
const isEdit = computed(() => {
  return agentId.value > 0;
});

// 用户选择相关
const userOptions = ref([]);
const userSearchLoading = ref(false);
const handleOpenCard = async () => {
  if (userStore.isTest) {
    ElMessage.warning("测试账号不能开卡");
    return;
  }

  if (!form.user_id) {
    ElMessage.error("请先选择关联用户");
    return;
  }

  const count = form.card_record || 0;
  if (count <= 0) {
    ElMessage.warning("请输入要开卡的次数");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确认为【${form.name || "该用户"}】开卡 ${count} 次吗？`,
      "开卡确认",
      {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const res = await baseOpenCard({
      user_id: form.user_id,
      count: form.card_record,
      remark: `代理开卡 - ${form.name || ""}`,
    });
    if (res.code === 0) {
      ElMessage.success("开卡成功");
      form.card_record = 0; // 清空输入
      getDetail(); // 重新刷新用户列表或记录
    } else {
      ElMessage.error("开卡失败");
    }
  } catch (err) {
    console.log(err);

    ElMessage.error("开卡失败");
  }
};

// 搜索用户
const searchUserRemote = async (query) => {
  if (query === "") {
    userOptions.value = [];
    return;
  }

  userSearchLoading.value = true;
  try {
    const res = await searchUsers(query);
    if (res.code === 0) {
      userOptions.value = res.data || [];
    } else {
      ElMessage.error(res.message || "搜索用户失败");
    }
  } catch (error) {
    console.error("搜索用户失败", error);
  } finally {
    userSearchLoading.value = false;
  }
};

// 上级代理佣金比例
const parentCommissionRate = computed(() => {
  const parent = parentOptions.value.find((p) => p.id === form.parent_id);
  return parent ? parent.commission_rate : null;
});

// 表单验证规则
const rules = reactive({
  name: [
    { required: true, message: "请输入代理名称", trigger: "blur" },
    { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" },
  ],
  level: [{ required: true, message: "请选择代理等级", trigger: "change" }],
  mobile: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: "blur" }],
  commission_rate: [
    { required: true, message: "请输入佣金比例", trigger: "blur" },
    { type: "number", message: "佣金比例必须为数字", trigger: "blur" },
  ],
  max_generation_count: [
    { required: true, message: "请输入激活码数量", trigger: "blur" },
    { type: "number", message: "数量必须为数字", trigger: "blur" },
  ],
  user_id: [{ required: true, message: "请选择关联用户", trigger: "change" }],
});

// 判断是否禁用提交按钮
const submitDisabled = computed(() => {
  return userStore.isTest || loading.value;
});

// 返回列表页
const goBack = () => {
  router.push("/agent/list");
};

// 获取代理详情
const getDetail = async () => {
  if (!isEdit.value) return;

  loading.value = true;
  try {
    const res = await getAgentDetail(agentId.value);
    console.log("获取代理详情响应:", res);
    if (res.code === 0) {
      // 更新表单数据 - 修正这里，直接使用data而不是data.agent
      Object.assign(form, res.data);

      // 如果有团队规模和团队业绩数据，也添加到form中
      if (res.data.stats) {
        form.team_size = res.data.stats.team_size;
        form.team_performance = res.data.stats.team_performance;
        form.remaining_count = res.data.stats.unused_codes;
      }
    } else {
      ElMessage.error(res.message || "获取代理详情失败");
    }
  } catch (error) {
    console.error("获取代理详情失败", error);
    ElMessage.error("获取代理详情失败");
  } finally {
    loading.value = false;
  }
};

// 获取所有可选的上级代理
const getParentOptions = async () => {
  try {
    const res = await getAgentList({ page: 1, per_page: 100 });
    if (res.code === 0) {
      parentOptions.value = res.data.items || [];
      // 编辑模式下，移除当前代理及其所有下级代理
      if (isEdit.value) {
        // 后端API会确保不会形成循环引用，这里不需额外处理
      }
    }
  } catch (error) {
    console.error("获取上级代理列表失败", error);
  }
};

// 监听上级代理变化，确保佣金比例合理
watch(
  () => form.parent_id,
  (newVal) => {
    if (newVal && parentCommissionRate.value !== null) {
      // 如果佣金比例大于上级，则自动调整
      if (form.commission_rate > parentCommissionRate.value) {
        form.commission_rate = parentCommissionRate.value;
        ElMessage.warning("佣金比例不能高于上级代理");
      }
    }
  }
);

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;

  // 测试账号权限检查
  if (userStore.isTest) {
    ElMessage.warning("测试账号不能修改代理信息");
    return;
  }

  await formRef.value.validate(async (valid, fields) => {
    if (!valid) {
      console.error("表单验证失败:", fields);
      ElMessage.error("请检查表单填写是否正确");
      return;
    }

    // 检查必填项
    if (!form.user_id) {
      ElMessage.error("请选择关联用户");
      return;
    }

    loading.value = true;
    try {
      // 处理parent_id为空字符串的情况
      if (form.parent_id === "") {
        form.parent_id = null;
      }

      // 打印提交数据
      console.log("提交的表单数据:", JSON.stringify(form));

      if (isEdit.value) {
        // 更新代理
        const res = await updateAgent(agentId.value, form);
        console.log("更新代理响应:", res);
        if (res.code === 0) {
          ElMessage.success("代理更新成功");
          goBack();
        } else {
          ElMessage.error(res.message || "更新失败");
        }
      } else {
        // 新增代理
        const res = await addAgent(form);
        console.log("添加代理响应:", res);
        if (res.code === 0) {
          ElMessage.success("代理添加成功");
          goBack();
        } else {
          ElMessage.error(res.message || "添加失败");
        }
      }
    } catch (error) {
      console.error("保存代理失败", error);
      if (error.response && error.response.data) {
        console.error("错误响应数据:", error.response.data);
        if (error.response.data.message) {
          ElMessage.error(error.response.data.message);
        } else {
          ElMessage.error("保存失败，请检查表单数据是否正确");
        }
      } else {
        ElMessage.error("保存失败，请检查网络连接");
      }
    } finally {
      loading.value = false;
    }
  });
};

// 手机号脱敏处理
const maskMobile = (mobile) => {
  if (!mobile) return "无手机号";
  return mobile.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2");
};

onMounted(() => {
  getParentOptions();
  getDetail();
});
</script>

<style scoped>
.agent-edit-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.tip-text {
  margin-top: 5px;
  font-size: 12px;
}
.ml-10 {
  margin-left: 10px;
}
.agent-info {
  margin-top: 20px;
}
.user-search-box {
  display: flex;
  align-items: center;
}
.user-search-box .el-select {
  width: 100%;
}
.info-icon {
  margin-left: 10px;
  color: #909399;
  cursor: pointer;
}
.user-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}
.user-mobile {
  color: #909399;
  font-size: 12px;
}
.agent-tag {
  margin-left: 10px;
  font-size: 10px;
  padding: 0 4px;
}
</style>
